<?php
	include 'conn.php';
	
	$logic = rawurldecode($_GET['logic']);
	$_GUID = rawurldecode($_GET['cid']);
	$_Ext = ".js";
	$_targetpath = __TEMPLATE__;
	$_logicFile = $logic.$_Ext;
	if (empty($logic)|| empty($_GUID)){die('Parameter is invalid');}
	clearonline();//clear online
	
	if(chkguid($_GUID) && chkonline($_GUID)){
		$html_js = file_get_contents($_targetpath.$_logicFile);
	}else{
		//die($result);authfailed.js
		$html_js = file_get_contents($_targetpath."authfailed.js");
	}
	
	header('Content-type: text/javascript');
	echo $html_js;
	
	
	
	
	/**
	 * clear overdue users
	 *
	 */
	function clearonline(){
		global $db;
		$sql = "DELETE FROM Card_online Where Timer<".(time()-600)."";
		$result = $db->row_query($sql);
	}
	/**
	 * verify GUID whether only one.
	 *
	 * @param string $_GUID
	 * @return unknown
	 */
	function chkonline($_GUID){
		global $db;
		$_ip = get_client_ip();
		$result = $db->row_select_one("Card_online","CardID='".$_GUID."'");
		if ($result){
			if ($result['ip']==$_ip){
				//更新在线时间，返回已经在状态
				$rows = array(
						"Timer"=>time()
				);
				$db->row_update("Card_online",$rows,"CardID='".$_GUID."'");
				return TRUE;
			}else{
				//return account logined.
				return TRUE;
			}
		}else{
			//不在线，写入在线列表
			$rows = array("CardID"=>$_GUID,
						   "ip"=>$_ip,
						   "Timer"=>time()
						   );
			$db->row_insert("Card_online",$rows);
			return TRUE;
		}
		
	}
	
	/**
	 * get user client ip address
	 *
	 * @return unknown
	 */
	
	function get_client_ip(){
		if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
			$ip = getenv("HTTP_CLIENT_IP");
		else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
			$ip = getenv("REMOTE_ADDR");
		else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
			$ip = $_SERVER['REMOTE_ADDR'];
		else
			$ip = "unknown";
		return($ip);
	}
	
	/**
	 * Authenticate users to submit the GUID with the rules
	 *
	 * @param unknown_type $_GUID
	 * @return unknown
	 */
	
	function chkguid($_GUID){
		global $db;
		$sql = "select * from List_Card Where CardID='$_GUID' AND Status=1";
		$result = $db->row_query_one($sql);
		if($result){
			//$rule = explode("-",$result['CardID']);
			$current_date = time();
			//if(count($rule)!=7){return FALSE;}
			if($result['overdue']<$current_date){
				//return('serial number has expired');
				return FALSE;
			}else{
				return TRUE;
			}	
		}else{
			return FALSE;
		}
	}
?>